package gw.com.android.ui.news;

import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import gw.com.android.presenter.BackTopPresenter;
import gw.com.android.presenter.http.CalendarRequest;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.interfaces.ReqCallBack;
import www.com.library.util.DeviceUtil;
import www.com.library.view.XRecyclerView;

public class CalendarFragment extends PushMsgTabFragment {

    private RelativeLayout rlEmpty;
    private RelativeLayout rlEmptyFilter;
    private XRecyclerView mListView;
    private CalendarAdapter mAdapter;
    private TextView mTvFilter;
    private ImageView mIvFilter;

    private CalendarArgs mArgs = new CalendarArgs();
    private boolean newDay = true;
    private CalendarArgs filterArgs;
    private List<CalendarRequest.CalendarData> mDatas;
    private CalendarHeadViewHolder mHeadViewHolder;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_calendar;
    }

    @Override
    protected void initLayoutView() {
        rlEmpty = (RelativeLayout) mRootView.findViewById(R.id.rl_empty);
        rlEmptyFilter = (RelativeLayout) mRootView.findViewById(R.id.rl_empty_filter);
        mTvFilter = (TextView) mRootView.findViewById(R.id.tv_filter);
        mIvFilter = (ImageView) mRootView.findViewById(R.id.iv_filter);
        mHeadViewHolder = new CalendarHeadViewHolder(this, mRootView.findViewById(R.id.rl_head), mRootView.findViewById(R.id.view_calendar));
        mListView = (XRecyclerView) mRootView.findViewById(R.id.rv_content);
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mListView.setPullRefreshEnabled(false);
        mAdapter = new CalendarAdapter(getActivity());
        mListView.setLoadingMoreEnabled(false);
        mListView.setAdapter(mAdapter);
        int x = DeviceUtil.instance().dip2px(15, getContext());
        int y = DeviceUtil.instance().dip2px(36, getContext());
        new BackTopPresenter(getActivity(), mListView).location(Gravity.BOTTOM | Gravity.RIGHT, x, y).calcNavigationBar(true);
        mListView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                requestCalendar();
            }

            @Override
            public void onLoadMore() {
            }
        });
        // 头部过滤变动回调
        mHeadViewHolder.setCallback(new CalendarHeadViewHolder.CalendarHeadViewCallback() {
            @Override
            public void onRefresh(Calendar date) {
                newDay = true;
                filterArgs = null;
                mArgs.calendar = date;
                mListView.setRefreshing(true);
                mTvFilter.setTextColor(getResources().getColor(R.color.color_v));
                mIvFilter.setImageResource(R.mipmap.a_calendar_screen_stateless);
            }

            @Override
            public void onFilter(CalendarArgs args) {
                filterArgs = args;
                refreshFilterUi(args);
            }
        });
    }

    private void refreshFilterUi(CalendarArgs args) {
        if (args == null || args.isEmpty()) {
            mTvFilter.setTextColor(getResources().getColor(R.color.color_v));
            mIvFilter.setImageResource(R.mipmap.a_calendar_screen_stateless);
            refreshUi(mDatas);
        } else {
            mTvFilter.setTextColor(getResources().getColor(R.color.color_k));
            mIvFilter.setImageResource(R.mipmap.a_calendar_screen_focus);

            List<CalendarRequest.CalendarData> data = filterData(args);
            mAdapter.updateData(data);
            int itemCount = mAdapter.getItemCount();
            if (itemCount <= 0) {
                rlEmpty.setVisibility(View.GONE);
                mListView.setVisibility(View.GONE);
                rlEmptyFilter.setVisibility(View.VISIBLE);
                mListView.setLoadingMoreEnabled(false);
                mListView.setNoMore(true);
            } else {
                rlEmpty.setVisibility(View.GONE);
                rlEmptyFilter.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
                mListView.setLoadingMoreEnabled(true);
                mListView.setNoMore(true);
            }
        }
        newDay = false;
    }

    private void refreshUi(List<CalendarRequest.CalendarData> list) {
        if (mAdapter == null) {
            return;
        }
        mDatas = list;
        if (!newDay) {
            // 同一天内，不管怎么刷新，都保留筛选结果
            if (filterArgs != null && !filterArgs.isEmpty()) {
                refreshFilterUi(filterArgs);
                return;
            }
        }
        mAdapter.updateData(list);
        mHeadViewHolder.resetFilterPopup();
        int itemCount = mAdapter.getItemCount();
        if (itemCount <= 0) {
            rlEmpty.setVisibility(View.VISIBLE);
            rlEmptyFilter.setVisibility(View.GONE);
            mListView.setLoadingMoreEnabled(false);
            mListView.setNoMore(true);
        } else {
            rlEmpty.setVisibility(View.GONE);
            rlEmptyFilter.setVisibility(View.GONE);
            mListView.setLoadingMoreEnabled(true);
            mListView.setNoMore(true);
        }
        newDay = false;
    }

    public boolean onBackPressed() {
        return mHeadViewHolder != null && mHeadViewHolder.onBackPressed();
    }

    @Override
    protected void initViewData() {
        List<CalendarRequest.CalendarData> list = new CalendarRequest(null).fetchLocal();
        if (list != null && !list.isEmpty()) {
            refreshUi(list);
        }
        mListView.setRefreshing(true);
    }

    /**
     * 本地数据筛选
     */
    public List<CalendarRequest.CalendarData> filterData(CalendarArgs args) {
        if (mDatas != null && !mDatas.isEmpty()) {
            List<CalendarRequest.CalendarData> result = new ArrayList<>();
            for (CalendarRequest.CalendarData data : mDatas) {
                if (data == null) {
                    continue;
                }
                if (args.countries != null && !args.countries.isEmpty()) {
                    if (!args.countries.contains(data.country)) {
                        continue;
                    }
                }
                if (CalendarArgs.STATUS_PRIVATE.equals(args.status)) {
                    if (!data.isFinanceData()) {
                        continue;
                    }
                    if (!TextUtils.isEmpty(data.value)) {
                        continue;
                    }
                } else if (CalendarArgs.STATUS_PUBLIC.equals(args.status)) {
                    if (!data.isFinanceData()) {
                        continue;
                    }
                    if (TextUtils.isEmpty(data.value)) {
                        continue;
                    }
                }
                if (args.level != null && !args.level.isEmpty()) {
                    if (!args.level.contains(String.valueOf(data.importanceLevel))) {
                        continue;
                    }
                }
                if (args.types != null && !args.types.isEmpty()) {
                    if (!args.types.contains(CalendarArgs.TYPE_DATA)) {
                        if (data.isFinanceData()) {
                            continue;
                        }
                    }
                    if (!args.types.contains(CalendarArgs.TYPE_EVENT)) {
                        if (data.isFinanceEvent()) {
                            continue;
                        }
                    }
                    if (!args.types.contains(CalendarArgs.TYPE_VACATION)) {
                        if (data.isFinanceVacation()) {
                            continue;
                        }
                    }
                }
                result.add(data);
            }
            return result;
        }
        return null;
    }

    public CalendarArgs getFilterArgs() {
        if (mDatas != null && !mDatas.isEmpty()) {
            CalendarArgs args = new CalendarArgs();
            for (CalendarRequest.CalendarData data : mDatas) {
                if (data == null) {
                    continue;
                }
                if (!TextUtils.isEmpty(data.country)) {
                    if (args.countries == null || !args.countries.contains(data.country)) {
                        args.addCountry(data.country);
                    }
                }
            }
            return args;
        }
        return null;
    }

    private void requestCalendar() {
        new CalendarRequest(mArgs).call(new ReqCallBack<List<CalendarRequest.CalendarData>>() {
            @Override
            public void onReqSuccess(List<CalendarRequest.CalendarData> result) {
                mListView.refreshComplete();
                refreshUi(result);
                mListView.setPullRefreshEnabled(false);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                mListView.refreshComplete();
                mListView.setNoMore(true);
                mListView.setPullRefreshEnabled(false);
            }
        });
    }

    @Override
    public void onRefresh() {
        mListView.setPullRefreshEnabled(true);
        mListView.smoothScrollToPosition(0);
        mListView.setRefreshing(true);
        requestCalendar();
    }

}
